import {UserControllerService} from "../../apis/index.js";
import {useRouter} from "vue-router";

const router = useRouter();

export default {
    namespaced: true,
    state: {
        loginUser: {}
    },
    getters: {
        loginUser: (state) => state.loginUser
    },
    actions: {
        async login({commit, state}, userInfo) {
            const username = userInfo.username.trim()
            const password = userInfo.password.trim()
            const res = await UserControllerService.login({username, password});
            if (res.code === 200 && res.data) {
                commit('setLoginUser', res.data);
                return true;
            }
            return res;
        },
        async getLoginUser({commit, state}) {
            const res = await UserControllerService.getCurrentUser();
            if (res.code === 200 && res.data) {
                commit('setLoginUser', res.data);
                return res.data;
            } else {
                commit('setLoginUser', {
                    userId: -1,
                    username: "未登录",
                });
            }
            return state.loginUser
        },
        async logout({commit}) {
            const res = await UserControllerService.logout();
            if (res.code === 200) {
                commit('setLoginUser', {
                    userId: -1,
                    username: "未登录",
                });
                return true;
            } else {
                return res.msg;
            }
        }
    },
    mutations: {
        setLoginUser(state, data) {
            state.loginUser = data;
        }
    },
}
